package com.chen.exception;

import com.chen.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/*
全局异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler//捕获异常
    public Result handleException(Exception e) {
        log.error("程序出错啦~~", e);
        return Result.error("出错啦，请联系陈世玉哥哥~~");
    }
    @ExceptionHandler
    public Result handleSQLIntegrityConstraintViolationException(DuplicateKeyException e) {
        log.error("数据库操作出错啦~~", e);
        String message = e.getMessage();
        int i= message.indexOf("Duplicate entry");
        String errorMsg=message.substring(i);
        log.error(errorMsg);
        String[] split = errorMsg.split(" ");
        return Result.error(split[2]+" 已存在!");
    }
    @ExceptionHandler
    public Result handleBuinessException(BusinessException businessException) {
        log.error("服务器异常", businessException);
        return Result.error(businessException.getMessage());
    }
}
